#include "ros/ros.h"
#include "logger.h"
#include "std_msgs/String.h"

class LoggerDemoNode {
public:
    LoggerDemoNode() {
        // 初始化日志系统
        log_system.InitLogger();
        log_system.DeleteOldestLogFiles();

        // 初始化ROS节点
        nh = ros::NodeHandle("~");
        
        // 创建发布者和订阅者
        pub = nh.advertise<std_msgs::String>("demo_topic", 10);
        sub = nh.subscribe("demo_topic", 10, &LoggerDemoNode::callback, this);

        // 记录初始化日志
        SPDLOG_INFO("ROS节点初始化完成");
    }

    ~LoggerDemoNode() {
        // 清理日志系统
        SPDLOG_INFO("ROS节点正在关闭");
        log_system.DestroyLogger();
    }

    void run() {
        ros::Rate rate(1); // 1Hz
        
        int count = 0;
        while (ros::ok()) {
            std_msgs::String msg;
            msg.data = "Hello ROS Logger " + std::to_string(count++);
            
            // 记录不同级别的日志
            SPDLOG_DEBUG("准备发布消息: {}", msg.data);
            pub.publish(msg);
            SPDLOG_INFO("已发布消息 #{}", count);
            
            if (count % 5 == 0) {
                SPDLOG_WARN("已发送{}条消息", count);
            }
            
            ros::spinOnce();
            rate.sleep();
        }
    }

private:
    void callback(const std_msgs::String::ConstPtr& msg) {
        try {
            // 模拟处理消息
            SPDLOG_DEBUG("收到消息: {}", msg->data);
            
            // 模拟偶尔发生的错误
            if (rand() % 10 == 0) {
                throw std::runtime_error("模拟随机错误");
            }
        } catch (const std::exception& e) {
            SPDLOG_ERROR("处理消息时出错: {}", e.what());
        }
    }

    ros::NodeHandle nh;
    ros::Publisher pub;
    ros::Subscriber sub;
    logger log_system;
};

int main(int argc, char** argv) {
    ros::init(argc, argv, "logger_demo_node");
    
    LoggerDemoNode node;
    node.run();

    return 0;
}